package com.jessechanrui.template.common.template.auth.application.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.jessechanrui.template.common.template.auth.application.dto.UserDTO;
import com.jessechanrui.template.common.template.auth.application.service.LoginService;
import com.jessechanrui.template.common.template.auth.application.service.TenantService;
import com.jessechanrui.template.common.template.auth.common.AuthorizationSupport;
import com.jessechanrui.template.common.template.auth.domain.User;
import com.jessechanrui.template.common.template.auth.domain.support.repository.UserRepository;
import com.jessechanrui.template.common.template.auth.exception.AuthCenterException;
import com.jessechanrui.template.common.template.auth.exception.UserException;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.AuthCenterFegin;
import com.jessechanrui.template.common.template.auth.infrastructure.feign.authcenter.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chenrui
 * @version 1.0
 * @description LoginServiceImpl
 * @date 2025/4/30
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AuthCenterFegin authCenterFegin;

    @Autowired
    private TenantService tenantService;

    @Override
    public UserDTO login(String userName, String password, String tenantId) {
        LoginResponse login = authCenterFegin.login(userName, password,false);
        if (BooleanUtil.isFalse(login.isSuccess())) {
            throw new AuthCenterException("用户认证失败");
        }

        String token = login.getContent().getAccessToken();

        if(StrUtil.isNotBlank(tenantId)){
            // 指定登录租户时，切换租户
            tenantService.switchTenant("Bearer " + token, tenantId);
        }
        AuthCenterTenant currentTenant = tenantService.getCurrentTenant("Bearer " + token);
        //租户ID
        AuthorizationSupport.setTenantId(currentTenant.getId());
        User user = userRepository.findByUserName(userName);
        if (ObjectUtil.isNull(user)) {
            throw new UserException("用户[" + userName + "]不存在，请在用户表中进行配置");
        }
        UserDTO userDTO = UserDTO.builder()
                .userNickname(user.getUserNickname())
                .name(user.getUserName())
                .userId(user.getUserId())
                .tenant(currentTenant)
                .isAdmin(false)
                .build();
        //平台管理员
        if ("agreeOwner".equals(userName)) {
            userDTO.setAdmin(true);
        }
        userDTO.setAccessToken(token);
        AuthorizationSupport.setUser(token, userDTO);
        return userDTO;
    }

    @Override
    public void logout() {
        AuthCenterBaseResponse<Object> response = authCenterFegin.logout(AuthorizationSupport.getCurrentUserToken());
        if (BooleanUtil.isFalse(response.isSuccess())) {
            throw new AuthCenterException("登出失败");
        }
    }

    @Override
    public UserDTO current(String accessToken) {
        if(accessToken != null && (!accessToken.startsWith("Bearer ") || !accessToken.startsWith("bearer "))) {
            accessToken = "Bearer " + accessToken;
        }
        UserDetailResponse userDetailResponse = authCenterFegin.currentUser(accessToken);
        if (BooleanUtil.isFalse(userDetailResponse.isSuccess())) {
            throw new AuthCenterException("获取用户信息失败");
        }

        AuthCenterTenant currentTenant = tenantService.getCurrentTenant(accessToken);
        AuthCenterUser authCenterUser = userDetailResponse.getContent();
        UserDTO userDTO = UserDTO.builder()
                .name(authCenterUser.getName())
                .userId(authCenterUser.getId())
                .userNickname(authCenterUser.getNickname())
                .accessToken(accessToken)
                .tenant(currentTenant)
                .build();

        if ("agreeOwner".equals(userDTO.getName()) || authCenterUser.isSuperAdmin()) {
            //TODO : 超级用户，暂定agreeOwner也为超级用户
            userDTO.setAdmin(true);
        }
        return userDTO;
    }
}
